package io.noties.markwon.app.sample.ui;

import io.noties.markwon.app.App;
import io.noties.markwon.app.ResourceTable;
import io.noties.markwon.app.sample.Sample;
import io.noties.markwon.app.utils.SampleUtilsKt;
import io.noties.prism4j.annotations.PrismBundle;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;

/**
 * @author: yangrui
 * @function: SampleCodeFragment
 * @date: 2021/3/23
 */
@PrismBundle(include = {"java", "kotlin"}, grammarLocatorClassName = ".GrammarLocatorSourceCode")
public class SampleCodeFragment extends Fraction {

    private Component progressBar;
    private Text textView;


    private final Sample sample;

    private SampleCodeFragment(Sample mObject) {
        this.sample = mObject;
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        return scatter.parse(ResourceTable.Layout_fragment_sample_code, container, false);
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        progressBar = getComponent().findComponentById(ResourceTable.Id_progress_bar);
        textView = (Text) getComponent().findComponentById(ResourceTable.Id_text_view);

        load();
    }

    private void load() {
        // TODO YR lack io.noties:adapt:2.2.0 and utils
        App.executorService.submit(() -> {

            Sample.Code code = SampleUtilsKt.readCode(textView.getContext(), sample);
/*

            Prism4j prism = new Prism4j(null); // new Prism4j(new GrammarLocatorSourceCode())
            Prism4jSyntaxHighlight highlight = Prism4jSyntaxHighlight.create(prism, Prism4jThemeDefault.create(0));
            String language = null;
            switch (code.getLanguage()) {
                case KOTLIN:
                    language = "kotlin";
                    break;
                default:
                case JAVA:
                    language = "java";
                    break;
            }
            CharSequence text = highlight.highlight(language, code.getSourceCode());
*/

            getFractionAbility().getUITaskDispatcher().syncDispatch(() -> {
                if (textView != null&&textView.getContext() != null) {
                    progressBar.setVisibility(Component.HIDE);
                    textView.setText(code.getSourceCode());
                }
            });

        });

    }

    private Sample getSample() {
        return sample;
    }

    private static String ARG_SAMPLE = "arg.Sample";

    public static SampleCodeFragment getInstance(Sample sample) {
        return new SampleCodeFragment(sample);
    }

}
